package netty.channel;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/*
* 实验目的：掌握对NIO中的channel使用
* 实验步骤：使用前面学习后的ByteBuffer(缓冲）和FileChannel(通道），将；小沙弥，真帅！“写入到file01.txt中
* */
public class NIOFileChannel01 {
    //创建ByteBuffer对象
    static   ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
    public static void main(String[] args) throws FileNotFoundException {
         writeFile();
         readFile();
    }


    //将字符串写入到文件中
    public static void writeFile() throws FileNotFoundException {
        String str="小沙弥 真帅！";
        //创建一个文件输入流
        FileOutputStream fileOutputStream = new FileOutputStream("/Users/zhangqilei/axzo/java/project/demos/demo/src/main/java/netty/channel/file01.txt");
        //通过文件输入流得到一个channel对象
        FileChannel channel = fileOutputStream.getChannel();
        //将数据写入到缓冲区中，并反转缓冲区
        byteBuffer.put(str.getBytes());
        byteBuffer.flip();
        try {
            channel.write(byteBuffer);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                //关闭文件输入流
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    //从文件中读取字符串显示到控制台
    public static void readFile() throws FileNotFoundException {
        FileInputStream fileInputStream = new FileInputStream("d:\\file01.txt");
        FileChannel channel = fileInputStream.getChannel();
        try {
            channel.read(byteBuffer);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        byteBuffer.flip();
        byte bytes[]=new byte[1024];
        bytes = byteBuffer.array();
        System.out.println(new String(bytes));
    }
}

